//
//  OrderDetailsViewController.m
//  SsehMaster
//
//  Created by 杨阳 on 2018/8/8.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "OrderDetailsViewController.h"
#import "OrderAddressTableViewCell.h"
#import "RequirementTableViewCell.h"
#import "PhotoTableViewCell.h"
#import "TroubleDescribeTableViewCell.h"
#import "OrderInforModel.h"
#import <MapKit/MapKit.h>
#import "AddMaterialsViewController.h"
#import "LabelLabelTableViewCell.h"
#import "LKImageScrollViewController.h"
#import "OrderCompleteUpLoadImageViewController.h"
#import "LXToolManager.h"
#import "orderRemarkInputViewController.h"
@interface OrderDetailsViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView * ssehTableView;

@property (nonatomic,strong) OrderDetail * materialModel;

@property (nonatomic,strong) NSMutableArray * freeMaterialMarr, * changeMaterialMarr;

@property (nonatomic,strong) UIButton * cancleOrderButton ,* repairButton,* navigationButton;

@property (nonatomic,strong) UIView * footerView;

@end

static NSString * const OrderAddressTableViewCellID = @"OrderAddressTableViewCellID";
static NSString * const RequirementTableViewCellID = @"RequirementTableViewCellID";
static NSString * const PhotoTableViewCellID = @"PhotoTableViewCellID";
static NSString * const TroubleDescribeTableViewCellID = @"TroubleDescribeTableViewCellID";
static NSString * const LabelLabelTableViewCellID = @"LabelLabelTableViewCellID";

@implementation OrderDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self baseSetting];
}

-(void)baseSetting{
    
    self.navigationItem.title = @"订单详情";
    self.navigationController.navigationBar.translucent = NO;
}

-(void)getData{
    
    //kGetMaintailOrderDetail
    NSDictionary * par = @{@"member_id":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserID)],
                           @"member_token":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserToken)],
                           @"order_id":self.orderModel.order_id
                           };
    [self showLoading];
    [[QYNetManager sharedManager]POST:kGetMaintailOrderDetail parameters:par andApiTyp:SsehApiTypGetOrders SuccessBlock:^(id responseObject) {
        [self hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            self.materialModel = [OrderDetail yy_modelWithDictionary:responseObject[@"data"]];
            [self separateDataSource];
            
        }else{
            [self showTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:SsehPoolNetStr];
    }];
}

-(void)separateDataSource{
    
    [self.freeMaterialMarr removeAllObjects];
    [self.changeMaterialMarr removeAllObjects];
    for (NSInteger i = 0; i < self.materialModel.maintailOrderMaterialBeans.count; i++) {
        
        MaterialInfo * model = self.materialModel.maintailOrderMaterialBeans[i];
        if (model.material_price.floatValue > 0) {
            [self.changeMaterialMarr addObject:model];
        }else{
            [self.freeMaterialMarr addObject:model];
        }
    }
    if (self.ssehTableView == nil) {
        [self layoutUI];
    }else{
        if (kStringIsEmpty(self.materialModel.order_maintail_imgs2)) {
            [self.cancleOrderButton setTitle:@"上传图片" forState:UIControlStateNormal];
        }else{
            [self.cancleOrderButton setTitle:@"查看图片" forState:UIControlStateNormal];
        }
        [self.ssehTableView reloadData];
    }
    [self handleButtonTitle];
    
    if (!kArrayIsEmpty(self.freeMaterialMarr)) {
        NSIndexPath * index = [NSIndexPath indexPathForRow:self.freeMaterialMarr.count-1 inSection:2];
        [self.ssehTableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }else{
        if (!kArrayIsEmpty(self.changeMaterialMarr)) {
            NSIndexPath * index = [NSIndexPath indexPathForRow:self.changeMaterialMarr.count-1 inSection:1];
            [self.ssehTableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
    }
    if ([self.materialModel.order_state isEqualToString:@"3"]) {
        
        
    }
}


-(void)handleButtonTitle{
    
    __weak typeof (self)weakSelf = self;
    NSInteger midButtonWidth = 0.1f;
    NSInteger rightButtonWidth = 0.1f;
    if ([self.materialModel.order_state isEqualToString:@"0"]) {//已关闭 显示已关闭
        
        self.cancleOrderButton.hidden = NO;
        self.navigationButton.hidden = YES;
        self.repairButton.hidden = YES;
        
        [self.cancleOrderButton setTitle:@"已关闭" forState:UIControlStateNormal];
        self.cancleOrderButton.userInteractionEnabled = NO;
    }else if ([self.materialModel.order_state isEqualToString:@"2"]){//待上门 都显示
        
        self.cancleOrderButton.hidden = NO;
        self.navigationButton.hidden = NO;
        self.repairButton.hidden = NO;
        
        [self.cancleOrderButton setTitle:@"取消订单" forState:UIControlStateNormal];
        [self.navigationButton setTitle:@"导航" forState:UIControlStateNormal];
        [self.repairButton setTitle:@"确认服务" forState:UIControlStateNormal];
        
        midButtonWidth = 0.1f;
        rightButtonWidth = 70.0f;
        
    }else if ([self.materialModel.order_state isEqualToString:@"3"]){//待确认 确认维修 取消订单
        self.cancleOrderButton.hidden = NO;
        self.navigationButton.hidden = YES;
        self.repairButton.hidden = NO;
        
        [self.cancleOrderButton setTitle:@"取消订单" forState:UIControlStateNormal];
        [self.repairButton setTitle:@"修改" forState:UIControlStateNormal];
        
        midButtonWidth = 0.1f;
        rightButtonWidth = 70.0f;
        
    }else if ([self.materialModel.order_state isEqualToString:@"4"] ||
              [self.materialModel.order_state isEqualToString:@"5"]){//已完成  显示已完成
        self.cancleOrderButton.hidden = NO;
        self.navigationButton.hidden = YES;
        self.repairButton.hidden = YES;
        
        if (kStringIsEmpty(self.materialModel.order_maintail_imgs2)) {
            [self.cancleOrderButton setTitle:@"上传图片" forState:UIControlStateNormal];
        }else{
            [self.cancleOrderButton setTitle:@"查看图片" forState:UIControlStateNormal];
        }
        
        self.cancleOrderButton.userInteractionEnabled = YES;
        
    }
    [self.repairButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.footerView);
        make.right.equalTo(weakSelf.footerView.mas_right).offset(-10);
        make.size.mas_equalTo(CGSizeMake(rightButtonWidth, 25));
    }];
    
    
    [self.navigationButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.footerView);
        make.right.equalTo(weakSelf.repairButton.mas_left).offset(-10);
        make.size.mas_equalTo(CGSizeMake(midButtonWidth, 25));
    }];
    
    
    [self.self.cancleOrderButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.footerView);
        make.right.equalTo(weakSelf.navigationButton.mas_left).offset(-10);
        make.size.mas_equalTo(CGSizeMake(70, 25));
    }];
    
}

-(void)layoutUI{
    
    self.ssehTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT-HOME_INDICATOR_HEIGHT-55-NAVIGATION_BAR_HEIGHT) style:UITableViewStyleGrouped];
    self.ssehTableView.delegate = self;
    self.ssehTableView.dataSource = self;
    self.ssehTableView.backgroundColor = [UIColor backGroudColorForView];
    self.ssehTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.ssehTableView.showsVerticalScrollIndicator = NO;
    self.ssehTableView.showsHorizontalScrollIndicator = NO;
    [self.ssehTableView registerNib:[UINib nibWithNibName:@"OrderAddressTableViewCell" bundle:nil] forCellReuseIdentifier:OrderAddressTableViewCellID];
    [self.ssehTableView registerNib:[UINib nibWithNibName:@"RequirementTableViewCell" bundle:nil] forCellReuseIdentifier:RequirementTableViewCellID];
    [self.ssehTableView registerNib:[UINib nibWithNibName:@"PhotoTableViewCell" bundle:nil] forCellReuseIdentifier:PhotoTableViewCellID];
    [self.ssehTableView registerNib:[UINib nibWithNibName:@"TroubleDescribeTableViewCell" bundle:nil] forCellReuseIdentifier:TroubleDescribeTableViewCellID];
    [self.ssehTableView registerNib:[UINib nibWithNibName:@"LabelLabelTableViewCell" bundle:nil] forCellReuseIdentifier:LabelLabelTableViewCellID];
    [self.view addSubview:self.ssehTableView];
    self.ssehTableView.estimatedRowHeight = 100;
    
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 100)];
    headerView.backgroundColor = [UIColor backGroudColorForView];
    self.ssehTableView.tableHeaderView = headerView;
    
    UIView * bgView = [UIView new];
    bgView.backgroundColor = RGBColor(31, 137, 255);
    [headerView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(headerView);
        make.top.equalTo(headerView);
        make.bottom.equalTo(headerView).offset(-10);
    }];
    
    //订单状态
    UILabel * orderStatyLabel = [UILabel new];
    if ([self.materialModel.order_state isEqualToString:@"0"]) {//已取消
        orderStatyLabel.text = @"已取消";
    }else if ([self.materialModel.order_state isEqualToString:@"1"]){//待指派
        orderStatyLabel.text = @"待指派";
    }else if ([self.materialModel.order_state isEqualToString:@"2"]){//待上门
        orderStatyLabel.text = @"待上门";
    }else if ([self.materialModel.order_state isEqualToString:@"3"]){//等待确认服务
        orderStatyLabel.text = @"等待确认服务";
    }else if ([self.materialModel.order_state isEqualToString:@"4"]){//待付款
        orderStatyLabel.text = @"待付款";
    }else if ([self.materialModel.order_state isEqualToString:@"5"]){//已付款
        orderStatyLabel.text = @"已付款";
    }
    
    orderStatyLabel.font = [UIFont systemFontOfSize:16];
    orderStatyLabel.textColor = [UIColor whiteColor];
    [bgView addSubview:orderStatyLabel];
    [orderStatyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView.mas_left).offset(10);
        make.top.equalTo(bgView.mas_top).offset(14);
    }];
    
    //订单编号
    UILabel * orderCodeLabel = [UILabel new];
    orderCodeLabel.text = [NSString stringWithFormat:@"订单编号：%@",self.materialModel.order_no];;
    orderCodeLabel.font = [UIFont systemFontOfSize:14];
    orderCodeLabel.textColor = [UIColor whiteColor];
    [bgView addSubview:orderCodeLabel];
    [orderCodeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(orderStatyLabel.mas_left);
        make.top.equalTo(orderStatyLabel.mas_bottom).offset(4);
    }];
    
    //创建时间
    UILabel * orderTimeLabel = [UILabel new];
    orderTimeLabel.text = [NSString stringWithFormat:@"创建时间：%@",self.materialModel.create_time];
    orderTimeLabel.font = [UIFont systemFontOfSize:14];
    orderTimeLabel.textColor = [UIColor whiteColor];
    [bgView addSubview:orderTimeLabel];
    [orderTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(orderStatyLabel.mas_left);
        make.top.equalTo(orderCodeLabel.mas_bottom).offset(4);
    }];
    
    //footerView
    __weak typeof (self)weakSelf = self;
    self.footerView = [UIView new];
    self.footerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.footerView];
    [self.footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.height.mas_equalTo(45);
        make.bottom.equalTo(weakSelf.view).offset(-HOME_INDICATOR_HEIGHT);
    }];
    
    //维修确认
    self.repairButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.repairButton.titleLabel.font = [UIFont systemFontOfSize:14];
    self.repairButton.layer.borderColor = [UIColor roseRed].CGColor;
    self.repairButton.layer.borderWidth = 1.0f;
    self.repairButton.layer.cornerRadius = 3.0f;
    [self.repairButton addTarget:self action:@selector(repairButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.repairButton setTitle:@"维修确认" forState:UIControlStateNormal];
    [self.repairButton setTitleColor:[UIColor roseRed] forState:UIControlStateNormal];
    [self.footerView addSubview:self.repairButton];
   
    //导航
    self.navigationButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.navigationButton.titleLabel.font = [UIFont systemFontOfSize:14];
    self.navigationButton.layer.borderColor = [UIColor roseRed].CGColor;
    self.navigationButton.layer.borderWidth = 1.0f;
    self.navigationButton.layer.cornerRadius = 3.0f;
    [self.navigationButton setTitle:@"导航" forState:UIControlStateNormal];
    [self.navigationButton setTitleColor:[UIColor roseRed] forState:UIControlStateNormal];
    [self.navigationButton addTarget:self action:@selector(navigationButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.footerView addSubview:self.navigationButton];
    
    //取消订单
    self.cancleOrderButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.cancleOrderButton.titleLabel.font = [UIFont systemFontOfSize:14];
    self.cancleOrderButton.layer.borderColor = RGBColor(185, 185, 185).CGColor;
    self.cancleOrderButton.layer.borderWidth = 1.0f;
    self.cancleOrderButton.layer.cornerRadius = 3.0f;
    [self.cancleOrderButton setTitle:@"取消订单" forState:UIControlStateNormal];
    [self.cancleOrderButton addTarget:self action:@selector(cancleOrderButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.cancleOrderButton setTitleColor:RGBColor(61, 66, 68) forState:UIControlStateNormal];
    [self.footerView addSubview:self.cancleOrderButton];
    
    NSInteger midButtonWidth = 0.1f;
    NSInteger rightButtonWidth = 0.1f;
    
    [self.repairButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.footerView);
        make.right.equalTo(weakSelf.footerView.mas_right).offset(-10);
        make.size.mas_equalTo(CGSizeMake(rightButtonWidth, 25));
    }];
    
    
    [self.navigationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.footerView);
        make.right.equalTo(weakSelf.repairButton.mas_left).offset(-10);
        make.size.mas_equalTo(CGSizeMake(midButtonWidth, 25));
    }];
    
    
    [self.self.cancleOrderButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.footerView);
        make.right.equalTo(weakSelf.navigationButton.mas_left).offset(-10);
        make.size.mas_equalTo(CGSizeMake(70, 25));
    }];
    
}
#pragma mark - - 拨打电话
-(void)callTheClient{
    [LXToolManager callThePhoneByNumber:self.materialModel.maintailOrderAddressBean.address_mobile];
}


#pragma mark- 确认维修
-(void)repairButtonClick:(UIButton *)button{
    
    AddMaterialsViewController * vc = [[AddMaterialsViewController alloc]init];
    vc.orderModel = self.materialModel;
    if (!kArrayIsEmpty(self.changeMaterialMarr) || !kArrayIsEmpty(self.freeMaterialMarr)) {
        vc.oldChargDataSource = self.changeMaterialMarr;
        vc.oldFreeDataSource = self.freeMaterialMarr;
    }
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark - 取消订单
-(void)cancleOrderButtonClick:(UIButton *)button{
    
    if ([self.materialModel.order_state isEqualToString:@"4"] ||
        [self.materialModel.order_state isEqualToString:@"5"]) {
        OrderCompleteUpLoadImageViewController * vc = [[OrderCompleteUpLoadImageViewController alloc]init];
        vc.orderModel = self.materialModel;
        if (kStringIsEmpty(self.materialModel.order_maintail_imgs2)) {
            vc.typ = @"1";
        }else{
            vc.typ = @"2";
        }
        [self.navigationController pushViewController:vc animated:YES];
        
        
    }else{
        UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self cancleOrder];
        }];
        UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:nil message:@"确认取消该订单？" preferredStyle:UIAlertControllerStyleAlert];
        [aleVC addAction:act1];
        [aleVC addAction:act2];
        [self presentViewController:aleVC animated:YES completion:nil];
    }
    
}

-(void)cancleOrder{
    
    //member_id    member_token  order_id
    [self showLoading];
    NSDictionary * par = @{@"member_id":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserID)],@"member_token":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserToken)],@"order_id":self.materialModel.order_no};
    [[QYNetManager sharedManager]POST:kRefuseWorkerOrder parameters:par andApiTyp:SsehApiTypGetOrders SuccessBlock:^(id responseObject) {
        [self hideLoading];
        DLog(@"%@",responseObject);
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:SsehPoolNetStr];
    }];
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        return 5;
    }else if (section == 1){
        return self.changeMaterialMarr.count;
    }else{
        return self.freeMaterialMarr.count;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 2 && indexPath.section == 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            LKImageScrollViewController * vc = [[LKImageScrollViewController alloc]init];
            vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
            NSArray * imageUrlArr = [self.materialModel.maintail_imgs componentsSeparatedByString:@","];
            NSMutableArray * imageStrMarr = [[NSMutableArray alloc]initWithCapacity:0];
            for (NSInteger i = 0; i < imageUrlArr.count; i++) {
                NSString * imageStr = [NSString stringWithFormat:@"%@",imageUrlArr[i]];
                NSString * urlStr = [NSString stringWithFormat:@"%@%@",kSsehImageIP,imageStr];
                [imageStrMarr addObject:urlStr];
            }
            vc.imgUrlArr = imageStrMarr;
            [self presentViewController:vc animated:YES completion:nil];
        });
    }else if (indexPath.section == 0 && indexPath.row == 4){
        orderRemarkInputViewController *orderInputVC = [[orderRemarkInputViewController alloc]init];
        orderInputVC.orderID = self.orderModel.order_id;
        orderInputVC.beforeString = self.orderModel.remark;
        [self.navigationController pushViewController:orderInputVC animated:YES];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            OrderAddressTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:OrderAddressTableViewCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.nameLabel.text = [NSString emptyStr:self.materialModel.maintailOrderAddressBean.address_name];
            cell.phoneLabel.text = [NSString emptyStr:self.materialModel.maintailOrderAddressBean.address_mobile];
            cell.addressLabel.text = [NSString stringWithFormat:@"%@%@%@%@%@",self.materialModel.maintailOrderAddressBean.address_province,self.materialModel.maintailOrderAddressBean.address_city,self.materialModel.maintailOrderAddressBean.address_country,self.materialModel.maintailOrderAddressBean.address_detailed,self.materialModel.maintailOrderAddressBean.address_road];
            cell.communityLabel.text = self.materialModel.maintailOrderAddressBean.address_detailed;
            cell.timeLabelLeft.text = [self serviceTime:self.materialModel.service_start_time andEndTime:self.materialModel.service_end_time andTyp:0];
            cell.timeLabelMid.text = [self serviceTime:self.materialModel.service_start_time andEndTime:self.materialModel.service_end_time andTyp:1];
            cell.timeLabelRight.text = [self serviceTime:self.materialModel.service_start_time andEndTime:self.materialModel.service_end_time andTyp:2];
            
            cell.phoneLabel.userInteractionEnabled = YES;
            UITapGestureRecognizer *callTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(callTheClient)];
            [cell.phoneLabel addGestureRecognizer:callTap];
            
            return cell;
        }else if (indexPath.row == 1){
            
            RequirementTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:RequirementTableViewCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell configData:self.materialModel.parts_names];
            return cell;
            
        }else if (indexPath.row == 2){
            
            PhotoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PhotoTableViewCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell configImage:self.materialModel.maintail_imgs];
            return cell;
            
        }else{
            TroubleDescribeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:TroubleDescribeTableViewCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.rightTextLabel.text = indexPath.row == 3?self.materialModel.maintail_remark:self.materialModel.remark;
            cell.leftTextLabel.text = indexPath.row == 3?@"问题描述:":@"备注:";
            cell.accessoryType = indexPath.row == 3?UITableViewCellAccessoryNone:UITableViewCellAccessoryDisclosureIndicator;
            
            
            return cell;
        }
    }else if (indexPath.section == 1){
        LabelLabelTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:LabelLabelTableViewCellID];
        MaterialInfo * model = self.changeMaterialMarr[indexPath.row];
        cell.leftLabel.text = model.material_name;
        CGFloat price = model.material_price.floatValue * model.material_count.floatValue;
        cell.rightLabel.text = [NSString stringWithFormat:@"¥%.2f",price];
        return cell;
    }else{
        LabelLabelTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:LabelLabelTableViewCellID];
        MaterialInfo * model = self.freeMaterialMarr[indexPath.row];
        cell.leftLabel.text = model.material_name;
        cell.rightLabel.text = [NSString stringWithFormat:@"¥%@",model.material_price];
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0.0001;
    }else if (section == 1){
        if (kArrayIsEmpty(self.changeMaterialMarr)) {
            return 0.0001;
        }else{
            return 50;
        }
    }else{
        if (kArrayIsEmpty(self.freeMaterialMarr)) {
            return 0.0001;
        }else{
            return 50;
        }
    }
    
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView * headerView = [UIView new];
    headerView.backgroundColor = [UIColor whiteColor];
    if (section == 1 && !kArrayIsEmpty(self.changeMaterialMarr)) {
        
        UIImageView * imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"repairList"]];
        [headerView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(headerView);
            make.left.equalTo(headerView).offset(20);
            make.size.mas_equalTo(CGSizeMake(12, 15));
        }];
        
        UILabel * titleLabel = [UILabel new];
        titleLabel.text = @"维修清单-收费项";
        titleLabel.textColor = RGBColor(51, 51, 51);
        titleLabel.font = [UIFont systemFontOfSize:14];
        [headerView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(imageView.mas_right).offset(5);
            make.centerY.equalTo(headerView);
        }];
        
        UIView * lineView = [UIView new];
        lineView.backgroundColor = [UIColor backGroudColorForView];
        [headerView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(headerView);
            make.height.mas_equalTo(1);
        }];
        
    }else if (section == 2 && !kArrayIsEmpty(self.freeMaterialMarr)) {
        
        UIImageView * imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"repairList"]];
        [headerView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(headerView);
            make.left.equalTo(headerView).offset(20);
            make.size.mas_equalTo(CGSizeMake(12, 15));
        }];
        
        UILabel * titleLabel = [UILabel new];
        titleLabel.text = @"维修清单-免费项";
        titleLabel.textColor = RGBColor(51, 51, 51);
        titleLabel.font = [UIFont systemFontOfSize:14];
        [headerView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(imageView.mas_right).offset(5);
            make.centerY.equalTo(headerView);
        }];
        
        UIView * lineView = [UIView new];
        lineView.backgroundColor = [UIColor backGroudColorForView];
        [headerView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(headerView);
            make.height.mas_equalTo(1);
        }];
        
    }
    
    return headerView;
}

-(NSString *)totlePriceForMaterial{
    
    float price = 0.0f;
    for (NSInteger i = 0; i < self.materialModel.maintailOrderMaterialBeans.count; i++) {
        MaterialInfo * model = self.materialModel.maintailOrderMaterialBeans[i];
        price += model.material_price.floatValue * model.material_count.floatValue;
    }
    
    return [NSString stringWithFormat:@"总金额： ¥%.2f",price];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if (section == 2 && (!kArrayIsEmpty(self.freeMaterialMarr) || !kArrayIsEmpty(self.changeMaterialMarr))) {
        return 50;
    }
    return 0.0001;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView * footerView = [UIView new];
    footerView.backgroundColor = [UIColor whiteColor];
    
    if (section == 2 && (!kArrayIsEmpty(self.freeMaterialMarr) || !kArrayIsEmpty(self.changeMaterialMarr))) {
        //totlePriceForMaterial
        UILabel * totlePrice = [UILabel new];
        totlePrice.textColor = [UIColor roseRed];
        totlePrice.text = [self totlePriceForMaterial];
        totlePrice.font = [UIFont systemFontOfSize:14];
        totlePrice.textAlignment = NSTextAlignmentRight;
        [footerView addSubview:totlePrice];
        [totlePrice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(footerView);
            make.right.equalTo(footerView.mas_right).offset(-20);
        }];
    }
    
    return footerView;
}

-(NSString *)serviceTime:(NSString *)startTime andEndTime:(NSString *)endTime andTyp:(NSInteger)typ{
    
    NSString * dateStr;
    switch (typ) {
        case 0://日期
            dateStr = [NSString stringWithFormat:@"%@/%@/%@",[NSString setNowTimeShow:0 andTimeStr:startTime],[NSString setNowTimeShow:1 andTimeStr:startTime],[NSString setNowTimeShow:2 andTimeStr:startTime]];
            
            break;
        case 1://日期
            dateStr = [NSString fromDateToWeek:startTime];
            
            break;
        case 2://日期
            dateStr = [NSString stringWithFormat:@"%@:%@-%@:%@",[NSString setNowTimeShow:3 andTimeStr:startTime],[NSString setNowTimeShow:4 andTimeStr:startTime],[NSString setNowTimeShow:3 andTimeStr:endTime],[NSString setNowTimeShow:4 andTimeStr:endTime]];
            break;
            
        default:
            dateStr = @"";
            break;
    }
    
    return dateStr;
}

#pragma mark - 导航

-(void)navigationButtonClick:(UIButton *)button{
    double lat = self.materialModel.maintailOrderAddressBean.address_latitude.doubleValue;
    double lon = self.materialModel.maintailOrderAddressBean.address_longitude.doubleValue;
    [self navigationAlert:CLLocationCoordinate2DMake(lat, lon)];
}

-(void)navigationAlert:(CLLocationCoordinate2D)coor{
    
    UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"用自带地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self iphoneMap:coor];
    }];
    
    UIAlertAction * act3 = [UIAlertAction actionWithTitle:@"用百度地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self baiduMap:coor];
    }];
    UIAlertAction * act4 = [UIAlertAction actionWithTitle:@"用高德地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self gaodeMap:coor];
    }];
    
    UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:nil message:@"请选择导航地图" preferredStyle:UIAlertControllerStyleActionSheet];
    [aleVC addAction:act1];
    [aleVC addAction:act2];
    [aleVC addAction:act3];
    [aleVC addAction:act4];
    
    [self presentViewController:aleVC animated:YES completion:nil];
    
}

-(void)iphoneMap:(CLLocationCoordinate2D)coor{
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com"]]){
        MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coor addressDictionary:nil]];
        [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                       launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,
                                       MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
    }else{
        [self showErrorTipWithTitle:@"未安装苹果地图"];
    }
    
}

-(void)baiduMap:(CLLocationCoordinate2D)coor{
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
        
        NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/ridenavi?destination=%f,%f&src=ios.baidu.openAPIdemo", coor.latitude, coor.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:urlString];
        [[UIApplication sharedApplication] openURL:url];
    }else{
        [self showErrorTipWithTitle:@"未安装百度地图"];
    }
}

-(void)gaodeMap:(CLLocationCoordinate2D)coor{
    
    NSURL *scheme = [NSURL URLWithString:@"iosamap://"];
    BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:scheme];
    if (!canOpen) {
        [self showErrorTipWithTitle:@"未安装高德地图"];
        return;
    }
    
    NSString * urlStr = [NSString stringWithFormat:@"iosamap://navi?sourceApplication=applicationName&poiname=fangheng&poiid=BGVIS&lat=%f1&lon=%f&dev=1&style=2",coor.latitude,coor.longitude];
    NSURL *myLocationScheme = [NSURL URLWithString:urlStr];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:myLocationScheme options:@{} completionHandler:^(BOOL success) {
            
        }];
    } else {
        [[UIApplication sharedApplication] openURL:myLocationScheme];
    }
    
}

-(NSMutableArray *)freeMaterialMarr{
    
    if (_freeMaterialMarr == nil) {
        _freeMaterialMarr = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _freeMaterialMarr;
}

-(NSMutableArray *)changeMaterialMarr{
    
    if (_changeMaterialMarr == nil) {
        _changeMaterialMarr = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _changeMaterialMarr;
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [self getData];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
